import { createStore } from '../vuex';

function customPlugin(store) {
  const local = localStorage.getItem('VUEX:STATE');
  if (local) {
    store.replaceState(JSON.parse(local));
  }
  store.subscribe((mutation, state) => {
    console.log('subscribe', state);
    localStorage.setItem('VUEX:STATE', JSON.stringify(state));
  });
}

const store = createStore({
  strict: true,
  plugins: [customPlugin],
  state () {
    return {
      count: 0
    }
  },
  getters: {
    double: state => state.count * 2
  },
  mutations: {
    add(state, payload) {
      state.count += payload;
    }
  },
  actions: {
    asyncAdd({ commit }, payload) {
      setTimeout(() => {
        commit('add', payload);
      }, 1000);
    }
  },
  modules: {
    aCount: {
      namespaced: true,
      state () {
        return {
          count: 0
        }
      },
      mutations: {
        add(state, payload) {
          state.count += payload;
        }
      },
      // modules: {
      //   cCount: {
      //     namespaced: true,
      //     state () {
      //       return {
      //         count: 0
      //       }
      //     },
      //     mutations: {
      //       add(state, payload) {
      //         state.count += payload;
      //       }
      //     },
      //   }
      // }
    },
    bCount: {
      namespaced: true,
      state () {
        return {
          count: 0
        }
      },
      mutations: {
        add(state, payload) {
          state.count += payload;
        }
      },
    }
  }
});
store.registerModule(['aCount', 'cCount'], {
  namespaced: true,
  state () {
    return {
      count: 0
    }
  },
  mutations: {
    add(state, payload) {
      state.count += payload;
    }
  },
});
export default store;
